package com.handa.documentManager.utils;

import com.handa.documentManager.entity.VO.FileDownloadResult;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class FileDownLoadUtil {

    public static FileDownloadResult downloadFile(String fileUrl) throws IOException {
        URL url = new URL(fileUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        try {
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(30000);
            connection.setReadTimeout(30000);

            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                throw new IOException("下载失败，HTTP状态码: " + connection.getResponseCode());
            }

            String contentType = connection.getContentType();
            long contentLength = connection.getContentLengthLong();

            try (InputStream inputStream = connection.getInputStream()) {
                byte[] data = inputStream.readAllBytes();
                return new FileDownloadResult(data, contentType, contentLength);
            }

        } finally {
            connection.disconnect();
        }
    }

    /**
     * 从URL获取文件名
     *
     * @param fileUrl 文件URL
     * @return 文件名
     */
    public static String getFileNameFromUrl(String fileUrl) {
        try {
            URL url = new URL(fileUrl);
            String path = url.getPath();
            String fileName = path.substring(path.lastIndexOf('/') + 1);

            // 如果URL中没有文件名，使用默认名称
            if (fileName.isEmpty()) {
                return "download_" + System.currentTimeMillis();
            }

            return fileName;
        } catch (Exception e) {
            return "file_" + System.currentTimeMillis();
        }
    }
}
